<template>
  <vidoTop></vidoTop>
  <el-dialog
      v-model="useAlerts.centerDialogVisible"
      width="35%"
      align-center
      @close="handleClose"
      style="
    background: url(https://uniapp213.oss-cn-beijing.aliyuncs.com/image/jianbian.png) no-repeat;
    background-size:100% 100%;
    border-radius: 10px;
    "
  >
    <div
        style="
        margin-bottom: 10px;
        display: flex;
        flex-direction: column;
        font-size: 16px;
        font-weight: 800;
      "
    >
      <span style="margin-bottom: 20px">登录后免费畅享高清视频</span>
      <div style="display: flex;justify-content: space-around;">
        <i class="iconfont icon-aixin" style="color: #fe2c55; font-size: 14px"
        >点赞评论随意发</i
        >
        <i class="iconfont icon-shipin" style="color: #fe2c55; font-size: 14px"
        > 投稿您的作品</i
        >
        <i class="iconfont icon-faxian" style="color: #fe2c55; font-size: 14px"
        >发现有趣世界</i
        >
      </div>
    </div>
    <div
        style="border: 1px solid #ccc; border-radius: 8px; background-color: #fff"
    >
      <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
        <el-tab-pane :label="babel" name="first">
          <div
              style="
      display: flex;
      flex-direction: column;
      align-items: center;
      margin-right: 10px;
    "
          >
            <el-form ref="passwordLogin1" :model="passwordLogin" :rules="passWordRules" v-if="!RetrievePassword">
              <el-form-item label="邮箱" label-width="80px" prop="emailNumber">
                <el-input
                    class="inputLogin"
                    placeholder="邮箱"
                    v-model="passwordLogin.emailNumber"
                />
              </el-form-item>
              <el-form-item label="密码" label-width="80px" prop="emailPassword" style="margin-bottom: 10px">
                <el-input
                    class="inputLogin"
                    placeholder="密码"
                    show-password
                    v-model="passwordLogin.emailPassword"
                />
                <p style="position: absolute;right: 5px;font-size: 12px;color: #de325b;" @click="Retrieve">忘记密码</p>
              </el-form-item>
            </el-form>
            <!-- 忘记密码 -->
            <el-form :model="RetrievePass" :rules="rules" v-if="RetrievePassword" ref="lossPassword">
              <el-form-item label="邮箱" label-width="80px" prop="emailNumber">
                <el-input
                    style="width: 250px;"
                    class="inputLogin"
                    placeholder="邮箱"
                    v-model="RetrievePass.emailNumber"
                />
              </el-form-item>
<!--              <el-form-item label-width="20" prop="code">-->
<!--                <div style="display: flex; justify-content: space-between; position: relative;">-->
<!--                  <el-input placeholder="请输入验证码" class="inputLogin" v-model="RetrievePass.code" />-->
<!--                  <el-button-->
<!--                      v-if="!countingDown"-->
<!--                      @click="reqcode('RetrievePass')"-->
<!--                      style="height: 26px; position: absolute; top: 2px; right: 1px; border: 0; border-left: 1px solid #ccc;"-->
<!--                      :plain="true"-->
<!--                  >获取验证码</el-button>-->
<!--                  <el-button v-else :plain="true" style="height: 26px; position: absolute; top: 2px; right: 1px; border: 0; border-left: 1px solid #ccc;">{{ countdown }}秒后再次获取</el-button>-->
<!--                </div>-->
<!--              </el-form-item>-->
              <el-form-item label="验证码" label-width="80px"  prop="code">
                <el-input v-model="RetrievePass.code" placeholder="请输入验证码" style="width: 250px;">
                  <template #append>
                    <el-button
                        v-if="!countingDown"
                        @click="reqcode('RetrievePass')"
                        :plain="true"
                    >获取验证码</el-button>
                    <span v-else>{{ countdown }}秒后再次获取</span>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item label="密码" label-width="80px" prop="password" style="margin-bottom: 30px">
                <el-input
                    style="width: 250px;"
                    class="inputLogin"
                    placeholder="请输入密码"
                    show-password
                    v-model="RetrievePass.password"
                />
              </el-form-item>
              <el-form-item label="确认密码" label-width="80px" prop="password1">
                <el-input
                    style="width: 250px;"
                    class="inputLogin"
                    placeholder="请确认密码"
                    show-password
                    v-model="RetrievePass.password1"
                />
              </el-form-item>
              <el-form-item label-width="80">
                <el-button :plain="true" @click="goBackLogin" style="width: 250px;">返回登录</el-button>
              </el-form-item>
            </el-form>
            <div
                style="
        display: flex;
        flex-direction: column;
        align-items: center;
        margin-top: 10px;
      "
                v-if="!RetrievePassword"
            >
              <img src="../../assets/image/bitbug_favicon.ico" alt=""/>
              <span
                  style="
          margin-top: 15px;
          margin-left: 18px;
          font-size: 16px;
          font-weight: 800;
          color: #fe2c55;
        "
              >登陆后即可点赞,收藏,评论哦！</span
              >
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="验证码登录" name="third">
          <!-- 验证码登录的地方 -->
          <div class="login-container">
            <el-form ref="codeLogin1" :model="codeLogin" :rules="rules1">
              <el-form-item label="邮箱" label-width="70px" prop="emailNumber">
                <el-input v-model="codeLogin.emailNumber" placeholder="请输入邮箱"/>
              </el-form-item>
              <el-form-item label="验证码" label-width="70px" prop="codePassword">
                <el-input v-model="codeLogin.codePassword" placeholder="请输入验证码">
                  <template #append>
                    <el-button
                        v-if="!countingDown"
                        @click="handleGetCode"
                        :plain="true"
                    >获取验证码</el-button>
                    <span v-else>{{ countdown }}秒后再次获取</span>
                  </template>
                </el-input>
              </el-form-item>
            </el-form>
            <div class="tips">
              <img src="../../assets/image/bitbug_favicon.ico" alt="">
              <span>登陆后即可点赞,收藏,评论哦！</span>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="注册" name="second">
          <div style="display: flex; flex-direction: column; align-items: center">
            <el-form ref="registerLogin1" :model="User" :rules="rules2">
              <el-form-item label="昵称" label-width="80" prop="username">
                <el-input
                    style="width: 250px"
                    placeholder="请输入昵称"
                    class="inputLogin"
                    v-model="User.username"
                />
              </el-form-item>
              <el-form-item label="邮箱" label-width="80" prop="email">
                <el-input
                    style="width: 250px"
                    placeholder="请输入邮箱"
                    class="inputLogin"
                    v-model="User.email"
                />
              </el-form-item>
              <el-form-item label="密码" label-width="80" prop="password" style="margin-bottom: 30px">
                <el-input
                    style="width: 250px"
                    placeholder="请输入密码"
                    show-password
                    class="inputLogin"
                    v-model="User.password"
                />
              </el-form-item>
              <el-form-item label="确认密码" label-width="80" prop="password1">
                <el-input
                    style="width: 250px"
                    placeholder="请确认密码"
                    class="inputLogin"
                    show-password
                    v-model="User.password1"
                />
              </el-form-item>
<!--              <el-form-item label="验证码" label-width="80px" prop="code">-->
<!--                <div-->
<!--                    style="display: flex; justify-content: space-between; position: relative;"-->
<!--                >-->
<!--                  <el-input-->
<!--                      placeholder="请输入验证码"-->
<!--                      class="inputLogin"-->
<!--                      v-model="User.code"-->
<!--                  />-->
<!--                  <el-button-->
<!--                      @click="reqcode('register')"-->
<!--                      style="height: 26px; position: absolute; top: 2px; right: 1px; border: 0; border-left: 1px solid #ccc;"-->
<!--                      v-if="!countingDown"-->
<!--                      :plain="true"-->
<!--                  >获取验证码</el-button>-->
<!--                  <el-button-->
<!--                      v-else-->
<!--                      :plain="true"-->
<!--                      style="height: 26px; position: absolute; top: 2px; right: 1px; border: 0; border-left: 1px solid #ccc;"-->
<!--                  >{{ countdown }}秒后再次获取</el-button>-->
<!--                </div>-->
<!--              </el-form-item>-->
              <el-form-item label="验证码" label-width="80px" prop="code">
                <el-input v-model="User.code" placeholder="请输入验证码" style="width: 260px">
                  <template #append>
                    <el-button
                        v-if="!countingDown"
                        @click="reqcode('register')"
                        :plain="true"
                    >获取验证码</el-button>
                    <span v-else>{{ countdown }}秒后再次获取</span>
                  </template>
                </el-input>
              </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>
      </el-tabs>

      <!-- 底部登录的地方 -->
      <div style="
          display: flex;
          flex-direction: column;
          align-items: center;
          margin-bottom: 10px;">
        <div style="display: flex;align-items: center;margin-left: 10px;">
          <el-checkbox v-model="checked2"></el-checkbox>
          <span style="margin-right: 60px;margin-left: 5px;">同意<i style="color: blue;margin: 0 5px">用户协议</i>和<i
              style="color: blue; margin: 0 5px">隐私协议</i></span>
        </div>
        <el-button
            style="
            background-color: #de325b;
            width: 300px;
            margin-left: 50px;
            margin-top: 5px;
            color: #fff;
          "
            v-if="!RetrievePassword"
            @click="goRegister"
        >登录/注册
        </el-button>
        <el-button
            style="
            background-color: #de325b;
            width: 300px;
            margin-left: 50px;
            margin-top: 5px;
            color: #fff;
          "
            v-if="RetrievePassword"
            @click="goRetrieve"
        >确认修改
        </el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import {reqUsercode, reqRegister, reqUserList, reqUserLogin, reqForgetPassword} from '../../api/home.js'
import vidoTop from '../vidoTop/index.vue'
import {ref, reactive} from "vue";
import {ElButton, ElMessage, ElNotification} from 'element-plus'
import {useAlertsStore} from '../../store/modules/home.js'
import {useRouter} from 'vue-router'

let useAlerts = useAlertsStore()
const activeName = ref("first")
let $router = useRouter()
// 用户协议是否勾选
let checked2 = ref(true)
// 验证码倒计时
let timer = ref(5);
// 验证码倒计时切换
let reqcode1 = ref(true);
const registerLogin1 = ref(null)
const codeLogin1 = ref(null)
const passwordLogin1 = ref(null)
// 控制忘记密码显示与隐藏
let RetrievePassword = ref(false)
let User = ref({
  username: '',
  email: "",
  password: "",
  password1: "",
  code: "",
});
let codeLogin = ref({
  emailNumber: '',
  codePassword: ''
})
let passwordLogin = ref({
  emailNumber: '',
  emailPassword: ''
})
let RetrievePass = ref({
  emailNumber: '',
  code: '',
  password: '',
  password1: '',
})
const handleClick = (tab, event) => {
  // console.log(tab, event)
}
// 登录或者注册
const goRegister = async () => {
  if (activeName.value === 'first') {
    let result1 = await reqUserLogin(passwordLogin.value)
    if (result1.code == '00000') {
      ElNotification({
        title: 'Error',
        message: result1.message,
        type: 'error',
      })
    } else {
      ElNotification({
        title: 'Success',
        message: result1.message,
        type: 'success',
      })
      saveUserInfo1(result1)
    }
    passwordLogin.value = {}
    useAlerts.checkDialog(false)
  } else if (activeName.value == 'third') {
    let result2 = await reqUserLogin(codeLogin.value)
    if (result2.code == '00000') {
      ElNotification({
        title: 'Error',
        message: result2.message,
        type: 'error',
      })
    } else {
      ElNotification({
        title: 'Success',
        message: result2.message,
        type: 'success',
      })
    }
    codeLogin.value = {}
    useAlerts.checkDialog(false)
  } else {
    let result3 = await reqRegister(User.value)
    if (result3.code == '00000') {
      ElNotification({
        title: 'Error',
        message: result3.message,
        type: 'error',
      })
    } else {
      activeName.value = 'first'
      ElNotification({
        title: 'Success',
        message: result3.message,
        type: 'success',
      })
    }
    User.value = {}
    useAlerts.checkDialog(false)
  }
}

const countingDown = ref(false);
const countdown = ref(60);

// 获取验证码的方法
// 获取验证码的方法
const handleGetCode = () => {
  if (!codeLogin.value.emailNumber) {
    ElMessage.error('请输入邮箱');
    return;
  }
  startCountdown();
  reqUsercode({email: codeLogin.value.emailNumber})
      .then(() => {
        ElMessage.success('验证码发送成功');
      })
      .catch((error) => {
        ElMessage.error('验证码发送失败: ' + error.message);
      });
};


// 开始倒计时的方法
const startCountdown = () => {
  countingDown.value = true; // 开始倒计时
  countdown.value = 60; // 设置倒计时时间为60秒
  const intervalId = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--; // 每秒减少倒计时时间
    } else {
      clearInterval(intervalId); // 清除倒计时
      countingDown.value = false; // 倒计时结束
      countdown.value = 0; // 重置倒计时时间
    }
  }, 1000);
};
const reqcode = async (params) => {
  if (params == 'code') {
    if(!codeLogin.value.emailNumber){
      ElMessage.warning('请先输入邮箱!!!')
      return
    }
    let res = await reqUsercode({email: codeLogin.value.emailNumber});
  } else if (params == 'RetrievePass') {
    if(!RetrievePass.value.emailNumber){
      ElMessage.warning('请先输入邮箱!!!')
      return
    }
    reqUsercode({email: RetrievePass.value.emailNumber})
  } else {
    if(!User.value.email){
      ElMessage.warning('请先输入邮箱!!!')
      return
    }
    let res = await reqUsercode({email: User.value.email});
  }
  ElMessage({
    message: "验证码发送成功",
    type: "success",
  });
  reqcode1.value = false;
  // let time = 0
  startCountdown()
  // time = setInterval(() => {
  //   timer.value--;
  //   if (timer.value <= 0) {
  //     reqcode1.value = true;
  //   }
  // }, 1000);
  // time = null;
};
// 找回密码的回调
let babel = ref('密码登录')
const Retrieve = () => {
  babel.value = '找回密码'
  RetrievePassword.value = true
}
const goBackLogin = () => {
  babel.value = '密码登录'
  RetrievePassword.value = false
}
// 确认新密码的回调
const goRetrieve = async () => {
  console.log(111);
  let res = await reqForgetPassword(RetrievePass.value)
  if (res.code == '00000') {
    ElMessage({
      showClose: true,
      message: res.message,
      type: 'warning',
    })
  } else {
    ElMessage({
      showClose: true,
      message: res.message,
      type: 'success',
    })
    RetrievePassword.value = false
  }

}
// 保存用户信息
const saveUserInfo1 = (UserInfo) => {
  useAlerts.saveUserInfo(UserInfo)
}
const validatePasswordStrength = (rule, value, callback) => {
  if (!value) {
    return callback(new Error('密码不能为空'));
  }

  const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^a-zA-Z\d]).{8,}$/;

  if (!passwordRegex.test(value)) {
    return callback(new Error('密码必须包含大小写字母、数字和符号，且长度至少为8位'));
  }

  callback();
};
// 验证码登录
const rules1 = reactive({
  emailNumber: [
    {required: true, message: '请输入正确的邮箱格式', trigger: 'blur'},
  ],
  codePassword: [
    {required: true, message: '请输入验证码', trigger: 'blur', min: 6, max: 6}
  ]
})
const validatePass = (rule, value, callback) => {
  if (value === "" || value != User.value.password) {
    callback(new Error("两次输入的密码不一致,请重新输入"));
  }
}
const validatePass1 = (rule, value, callback) => {
  if (value === "" || value != RetrievePass.value.password) {
    callback(new Error("两次输入的密码不一致,请重新输入"));
  }
}
// 注册
const rules2 = reactive({
  username: [
    {
      required: true,
      message: "请输入昵称",
      trigger: "blur",
    },
  ],
  email: [
    {
      required: true,
      message: "请输入邮箱地址",
      trigger: "blur",
    },
    {
      validator: (rule, value, callback) => {
        if (value === '') {
          callback(new Error("请输入邮箱地址"));
        } else if (!isvalidEmail(value)) {
          callback(new Error("请输入正确的邮箱格式"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  password: [
    {
      required: true,
      message: "请输入密码",
      trigger: "blur",
    },
    {
      validator: validatePasswordStrength,
      trigger: "blur",
    },
    // 密码强度验证规则
  ],
  password1: [
    {
      required: true,
      message: "请再次输入密码",
      trigger: "blur",
    },
    {
      validator: validatePass,
      trigger: "blur",
    },
  ],
  code: [
    {
      required: true,
      min: 6,
      max: 6,
      message: "请输入验证码",
      trigger: "blur",
    },
  ],
});
// 密码强度校验函数


const rules = reactive({
  emailNumber: [
    {
      required: true,
      message: '请输入邮箱地址',
      trigger: 'blur',
    },
    {
      validator: (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入邮箱地址'));
        } else if (!isvalidEmail(value)) {
          callback(new Error('请输入正确的邮箱格式'));
        } else {
          callback();
        }
      },
      trigger: 'blur',
    },
  ],
  code: [
    {
      required: true,
      message: '请输入验证码',
      trigger: 'blur',
    },
  ],
  password: [
    {
      required: true,
      message: "请输入密码",
      trigger: "blur",
    },
    {
      validator: validatePasswordStrength,
      trigger: "blur",
    },
    // 密码强度验证规则
  ],
  password1: [
    {
      required: true,
      message: "请再次输入密码",
      trigger: "blur",
    },
    {
      validator: validatePass1,
      trigger: "blur",
    },
  ],
});


const passWordRules = reactive({
  emailNumber: [
    {
      required: true,
      message: '请输入邮箱地址',
      trigger: 'blur',
    },
    {
      validator: (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入邮箱地址'));
        } else if (!isvalidEmail(value)) {
          callback(new Error('请输入正确的邮箱格式'));
        } else {
          callback();
        }
      },
      trigger: 'blur',
    },
  ],
  emailPassword: [
    {
      required: true,
      message: "请输入密码",
      trigger: "blur",
    },
    // 密码强度验证规则
  ]
});
// 邮箱验证函数
function isvalidEmail(email) {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return emailRegex.test(email);
}
const lossPassword = ref(null)
const handleClose = () => {
    RetrievePass.value = {
    emailNumber: '',
    code: '',
    password: '',
    password1: '',
  }
  if (passwordLogin1.value) passwordLogin1.value.resetFields();
  if (codeLogin1.value) codeLogin1.value.resetFields();
  if (registerLogin1.value) registerLogin1.value.resetFields();
  if (lossPassword.value) registerLogin1.value.resetFields();
};
</script>

<style scoped lang="less">
.demo-tabs {
  height: 300px;
}

.inputValue {
  height: 40px;
  margin-left: 200px;
  outline: none;
  border-radius: 5px;
}

.inputLogin {
  width: 220px;
}

:deep(.el-tabs__nav-scroll) {
  display: flex;
  justify-content: center;
}

:deep(.el-tabs__nav-wrap::after) {
  content: "";
  width: 0;
}

:deep(.el-input__wrapper) {
  background-color: transparent;
  outline: none;
}

.login-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-right: 10px;
}

.tips {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 10px;
}

.tips img {
  margin-right: 10px;
}

</style>
